package com.lvmama.pangolin.timer.processor;




import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.lvmama.pangolin.busi.config.ConfigManager;
import com.lvmama.pangolin.common.DateUtil;
import com.lvmama.pangolin.entity.Timer;
import com.lvmama.pangolin.service.TimerService;
import com.lvmama.pangolin.timer.CommonJob;
import com.lvmama.pangolin.util.SpringContextUtil;


public class MoveTimerToHistory extends CommonJob {

	@Autowired
	private TimerService timerService;
	@Autowired 
	private CheckSpiderDate checkSpiderDate;
	
	private Logger logger = Logger.getLogger(MoveTimerToHistory.class);
	@Override
	public void runJob(JobExecutionContext context, String parameter)
	{
		try
		{
			
			logger.info("完成timer数据搬移历史表开始...");
			if(timerService == null)
			{
				timerService = (TimerService) SpringContextUtil.getBean(TimerService.class);
			}
			
			String syscode=System.getProperties().getProperty("SYSCODE");
			ConfigManager config = ConfigManager.getInstance();
			//处理状态为2的Timer数据
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("syscode", syscode);
			List<String> statusList = new ArrayList<String>();
//			statusList.add("0");
//			statusList.add("1");
			statusList.add("2");
			statusList.add("3");
			map.put("timer_status", statusList);
			List<Timer> timer2List =  timerService.queryTimerListByCon(map);
			List<Timer> timer2L = new ArrayList<Timer>();
			if(timer2List != null && !timer2List.isEmpty())
			{
				Date currentdate = new Date();
				Calendar ccal = Calendar.getInstance();  
				ccal.setTime(currentdate);  
				//间隔超过几个小时
				String interVal = config.getParamValue(parameter, "INTERVAL", "2");
				ccal.add(Calendar.HOUR_OF_DAY, -Integer.valueOf(interVal));
				Map<String ,Object> paramMap = new HashMap<String ,Object>();
				for (Timer timer2 : timer2List)
				{
			        String cron = timer2.getTimer_cron();
					Date cronDate = DateUtil.getDateFromCron(cron);
					Calendar cal2 = Calendar.getInstance();
					cal2.setTime(cronDate);
			        if(cal2.compareTo(ccal) < 0)
			        {
			        	timer2L.add(timer2);
			        	paramMap.put("timer_id", timer2.getTimer_id());
			        	paramMap.put("error_desc", "抓取超过一定时间，默认成功，超时时间（小时）：" +interVal);
			        	paramMap.put("timer_status", "5");
			        	timerService.updateTimerByCon(paramMap);
			        }
				}
			}
			Timer timer  = new Timer();
			timer.setSyscode(syscode);
			timer.setTimer_status("5");
			List<Timer> timerList =  timerService.queryTimerList(timer);
			int count = 0;
			if(timerList != null && !timerList.isEmpty())
			{
				count = timerList.size();
				timerService.moveTimerToHistory(timerList);
				if(checkSpiderDate == null)
				{
					checkSpiderDate = (CheckSpiderDate) SpringContextUtil.getBean(CheckSpiderDate.class);
				}
				checkSpiderDate.checkSpider(timerList);
			}
			logger.info("完成timer数据搬移历史表结束... count: " + count);
			
			//是否需要对状态为0的错过执行时间的任务进行重新开启，只针对抓取的特定任务
			String flag = config.getParamValue(parameter, "DEAL_INVALID", "0");
			if("1".equals(flag))
			{
				dealInvalidPythonTimer(syscode,parameter);
			}
			
		}catch (Exception e)
		{
			logger.error("timer数据搬移历史失败!",e);
		}
	}
	
	
	private void dealInvalidPythonTimer(String  syscode,String configParam)
	{
		logger.info("处理过期未执行的timer开始...");
		Timer timer = new Timer();
		timer.setExec_mode("1");
		timer.setTimer_status("0");
		timer.setSyscode(syscode);
		List<Timer> timerList = timerService.queryTimerList(timer);
		if(timerList != null && !timerList.isEmpty())
		{
			String className = "com.lvmama.pangolin.timer.processor.PythonActor";
			
			Date currentdate = new Date();
			Calendar ccal = Calendar.getInstance();  
			ccal.setTime(currentdate);
			//失效30分钟
			ConfigManager config = ConfigManager.getInstance();
			String interVal = config.getParamValue(configParam, "INVALID_INTERVAL", "30");
			ccal.add(Calendar.MINUTE, -Integer.valueOf(interVal));
			Map<String,Object> param = new HashMap<String,Object>();
			
			
			param.put("oper_time", new Timestamp(new Date().getTime()));
			for (Timer timer2 : timerList)
			{
				try
	        	{
					if(!className.equalsIgnoreCase(timer2.getTimer_classname()))
					{
						continue;
					}
					String cron = timer2.getTimer_cron();
					Date cronDate = DateUtil.getDateFromCron(cron);
					Calendar cal2 = Calendar.getInstance();
					cal2.setTime(cronDate);
					param.put("timer_id", timer2.getTimer_id());
					//当天任务重执行，非当天任务改成5，默认成功
					if(cal2.compareTo(ccal) < 0)
			        {
						if(DateUtil.sameDate(currentdate,cronDate))
						{
							param.put("timer_status", "1");
							param.put("timer_type", "PYTHON");
				        	timerService.updateTimerByCon(param);
						}
						else
						{
							param.put("timer_status", "5");
							param.put("error_desc", "非当天失效任务,默认成功");
							timerService.updateTimerByCon(param);
						}
						
			        }
					
	        	}catch(Exception e)
	        	{
	        		logger.info("更新timer状态失败! timer_id :" +  timer2.toString());
	        	}
		       
			}
			
		}
		
		logger.info("处理过期未执行的timer完成 ...");
		
	}
	

}
